#[derive(Debug)]
struct Stack<T> {
    top: Option<Box<StackNode<T>>>,
}

#[derive(Clone, Debug)]
struct StackNode<T> {
    data: T,
    next: Option<Box<StackNode<T>>>,
}

impl <T> StackNode<T> {
    fn new(data: T) -> Self {
        StackNode {data: data, next: None}
    }
}

impl <T> Stack<T> {
    fn new() -> Self {
        Self{top: None}
    }

    fn push(&mut self, data: T) {
        let mut node = StackNode::new(data);
        let next = self.top.take();
        node.next = next;
        self.top = Some(Box::new(node));
    }

    fn pop(&mut self) -> Option<T> {
        let val = self.top.take();
        match val {
            None => None,
            Some(mut x) => {
                self.top = x.next.take();
                Some(x.data)
            },
        }
    }
}

fn npe_test() {
    #[derive(Debug)]
    struct MyStruct {
        value:i32,
    }

    let mut option: Option<MyStruct> = None;
    println!("after call take of None, what will happen.{:#?}", option.take());

    // there will be a runtime exception
    // called `Option::unwrap()` on a `None` value
    // but we can call take function of None, why?
    let my_struct = option.unwrap(); 
    println!("{}", my_struct.value);
}

fn main() {
    npe_test();
    let mut ss = Stack::new();
    println!("{:#?}", ss.top);
    // i don't know why no panic here
    // because ss.top is None, and in pop function, we call 
    // the take function of ss.top
    ss.pop();
    ss.push(1);
    ss.push(2);
    ss.push(3);

    println!("{:#?}", ss);
    ss.pop();
    ss.pop();
    println!("{:#?}", ss);
}